
// 数据准备
const confObj = JSON.parse(readConfigString('confJSON') || '{}')

const usermobile = confObj.user_mobile
const start_price = confObj.start_price
const end_price = confObj.end_price
const userAddress = confObj.user_address
const communitys = (confObj.user_communitys|| '').split('/')
const userkey = confObj.user_key
const deviceId = device.getIMEI()


let goodsList = [];
let currentIndex = 0
let userHasPayGoods = 0
let page = 1
let pageSize = 50
let radomAddr = '' // 随机地址

const host = 'https://api.zhiz.asia'

const apiUrl = {
    login:'/v1/login',
    product:'/v1/get-product',
    record:'/v1/add-records',
    countnew:'/v1/count-new'
}

const pageUserStore = storages.create("pageUser");

logd('脚本js加载')


function main() {

    //重置变量
    toast('脚本启动成功！');
    // 获取权限
    getUserRight()
    if (userkey && deviceId) {
        const result = checkUser()
        if (result.code === 0) {
            getNewCount()
        }
    } else {
        logd('没有获取到用户账号！');
    }
}

// 判断绑定情况
function checkUser() {
    logd('获取用户信息！');
    let params = {
        device_id: deviceId,
        user_key: userkey
    };
    // 失效直接在服务器端判断
    const result = usePost(host + apiUrl.login,params)
    logd('result',result,typeof result)
    if (result.code === 0) {
        return result
    }  else {
        toast(result.message)
        exit()
    }
}


// 下载服务器商品链接
function loadRemoteList() {
    logd('获取远程列表！');
    let params = {
        user_key: userkey,
        page:page,
        size:pageSize
    }
    const result = usePost(host + apiUrl.product,params)
    if (result.code === 0) {
        goodsList = result.data.data

        if(goodsList && goodsList.length){
            toast("本次获取："+goodsList.length+"件商品！开始下单")
            if(page === 1){
                openApp()
            }
        }else{
            toast(`未获取到商品！即将退出程序`)
            exit()
        }
        
    } else {
        toast(result.message)
    }
}

function getNewCount(){

    const result = usePost(host + apiUrl.countnew,{ user_key: userkey})

    if(result.code===0){
        toast("今日新增"+result.data+"件商品！")
        sleep(2000)
        loadRemoteList()
    }

}


// 判断app存在 打开app
function openApp() {
    logd("脚本执行：打开app");
    let count = 1;
    while (true) {
        sleep(500)
        if (text('淘宝')) {
            logd('找到了淘宝，可以执行打开操作')
            let res = utils.openAppByName("淘宝")
            sleep(2000);
            if (res) {
                judgeMainPage()
            }
            break;
        }
        logd('第' + count + '次查找启动！未找到')
        count++;
        if (count > 20) {
            toast('没有找到QQ应用')
            break;
        }
    }
}

// 判断是否在首页
function judgeMainPage() {
    let count = 1
    while (true) {
        const tiaozhuan = desc('跳转到首页')
        const guanzhu = text('关注')
        const dingyue = text('订阅')
        const tuijian = text('推荐')
        const activeGz = desc('关注已选中')
        const activeGy = desc('订阅已选中')
        const activeTj = desc('推荐已选中')
        if ( has(tiaozhuan) ||((has(guanzhu) || has(dingyue)) && has(tuijian) && (has(activeGz) || has(activeTj) || has(activeGy)))) {
            toast('已在首页!可以开始查找了')
            logd('已在首页!可以开始查找了')
            findFirstInput()
            return;
        } else {
            count++;
            if (count > 10) {
                break;
            }
        }
    }
    findMainPage()
}

function findMainPage() {
    let count = 0
    while (true) {
        logd('查找首页中')
        const shouye = desc('首页').getOneNodeInfo(1000)
        if (shouye) {
            logd('已找到首页')
            shouye.click()
            break
        } else {
            if (count % 10 === 0) {
                logd('返回上一层，继续查找')
                back()
                break;
            }
        }
    }
    sleep(5000)
    judgeMainPage()
}

// 找到搜索框 输入内容进行搜索
function findFirstInput() {
    const search1 = desc('搜索栏').getOneNodeInfo(1000);
    const search2 = desc('搜索').getOneNodeInfo(1000);
    const search = search1 || search2;
    // 输入商品列
    if (search) {
        let res = search.click()
        if (res) {
            sleep(1000);
            handlerSearch()
        }
    }
}

// 搜索页面找到输入框
function handlerSearch() {
    logd('已到达搜索页面 准备找到输入框')
    let count = 1
    while (true) {
        const node = id('com.taobao.taobao:id/searchEdit').getOneNodeInfo(1000);

        logd('search-node', node)
        if (node) {
            logd('总商品数：' + goodsList.length + ';开始搜索第' + (currentIndex + 1) + '个商品。')
            node.inputText((goodsList[currentIndex]||{}).product_buy)
            sleep(1000)
            let sear = desc('搜索').getOneNodeInfo(1000)
            if (sear) {
                sear.click()
            }
            break;
        } else {
            logd("第" + count + "次查找，无节点");
            sleep()
            count++;
            if (count > 10) {
                return;
            }
        }

    }
    sleep(3000)
    judgeIsSafe()
}

// 确定价格是否满足设置要求
function judgeIsSafe() {
    logd('查看商品是否有效')

    if(has(text('商品不能购买')) || has(text('失效宝贝'))){
         logd('该商品已失效')
        toast('该商品已失效,马上返回重新开始！');
        currentIndex++;
        userBack()
        return
    }

    //  包邮
    logd('商品有效，比对包邮情况！')
    if (!desc('快递 免邮') || !desc('包邮')) {
        toast('不包邮，返回！')
        logd('不包邮，返回')
        back()
        return false
    }
    logd('比对价格！')
    let count = 1
    // 价格
    while (true) {
        let hej1 = desc('合计:').getOneNodeInfo(1000)
        let hej2 = text('合计:').getOneNodeInfo(1000)
        let hej = hej1 || hej2
        if (hej) {
            while (true) {
                let price = hej.nextSiblings()[0]
                logd('price',price)
                if (price && price.text) {
                    let str = price.text.replace('￥', '') - 0
                    if (str >= start_price && str <= end_price) {
                        logd('价格为：' + str + ';满足设置的' + start_price + '--' + end_price + '之间，可以下单。')
                        createUserMsg()
                        return
                    } else {
                        toast('价格不满足要求，返回')
                        logd('价格不满足要求，返回')
                         logd('价格为：' + str + ';不满足设置的' + start_price + '--' + end_price + '之间，价格不满足要求。')
                        currentIndex++;
                        userBack()
                        return
                    }
                } else {
                    count++;
                    if (count > 30) {
                        toast('未能正确比对价格，返回')
                        logd('未能正确比对价格，返回')
                        currentIndex++;
                        userBack()
                        return
                    }
                }
            }
        } else {
            count++;
            if (count > 30) {
                toast('未能正确比对价格，返回')
                logd('未能正确比对价格，返回')
                currentIndex++;
                 userBack()
                break
            }
        }
    }
}


function userBack() {
    back()
    sleep(800)
    let count = 0
    while (true) {
        sleep(500)
        const edit = desc('下次再编辑').getOneNodeInfo(1000)
        if (edit) {
            edit.click()
            sleep(1000);
            break;
        } else {
            count++;
            if (count % 5 === 0) {
                break;
            }
        }
    }
    judgeMainPage()
}

// 生成地址 创建地址以及联系人
function createUserMsg() {
    while (true) {
        sleep(500)
        let jumpNode = desc('点击查看收货地址').getOneNodeInfo(1000);
        if (jumpNode) {
            sleep(500)
            logd('跳转到查看收货地址页面')
            jumpNode.click()
            sleep(2000)
            getAddress()
            return
        }
    }

}

// 地址处理
function getAddress() {
    let count = 0
    while (true) {
        sleep(500)
        const node = desc('添加收货地址').getOneNodeInfo(1000);
        if (node) {
            node.click()
            sleep(2000);
            logd('跳转到生成地址页面')
            saveAddress()
            return
        } else {
            count++
            if (count % 10 === 0) {
                break
            }
        }
    }
}

function saveAddress() {
    let addr = userAddress + communitys[random(0, communitys.length - 1)] + random(1, 66) + '栋' + random(1, 9) + '' + random(10, 99);
    const name = firstName[random(0, firstName.length - 1)] + lastName[random(0, lastName.length - 1)]
    radomAddr = name + '，' + usermobile + '，' + addr
    logd('随机生成的地址：' + radomAddr)
    while (true) {
        const selector = textMatch("粘贴收货信息到此处.*").getOneNodeInfo(1000)
        if (selector && selector.click()) {
            logd('跳转到智能添加页面！')
            sleep(2000);
            textMatch("粘贴收货信息到此处.*").getOneNodeInfo(1000).inputText(radomAddr)
            sleep(2000);
            desc('识别').getOneNodeInfo(2000).click();
            sleep(2000);
            desc('默认收货地址').getOneNodeInfo(1000).click()
            sleep(1000);
            desc('保存').getOneNodeInfo(2000).click();
            logd('地址保存成功！返回提交订单！')
            sleep(2000)
            submitOrder()
            break
        } else {
            logd('点击失败！')
        }
    }
}

// 提交订单 输入密码支付
function submitOrder() {
    let count = 0
    while (true) {
        sleep(500)
        const order = desc('提交订单').getOneNodeInfo(1000);
        if (order) {
            if (order.click()) {
                logd('调用支付宝的免密支付')
                handlerResult()
                break;
            } else {
                logd('提交订单点击失败！')
            }
        } else {
            count++;
            if (count % 50 === 0) {
                toast('提交订单查找失败！');
                break
            }
        }
    }
}

function handlerResult() {
    if(currentIndex === goodsList.length-1){
        page++;
        loadRemoteList()
    }
    let count = 0
    let checkStatus = 0;
    let canGo = 0
    const cgood = goodsList[currentIndex]
    while (true) {
        sleep(1000);
        userFindImg('zhifuchenggong.png', function (points) {
            logd('zhi图片查找的返回' + JSON.stringify(points))
            if (points && points.length > 0) {
                toast('支付成功！')
                userHasPayGoods++;
                checkStatus = 1

                recordInfo({
                    status:1,
                    status_name:'支付成功！',
                    user_key:userkey,
                    user_info:radomAddr,
                    product_name:cgood.product_name,
                    product_id:cgood.product_id,
                    product_buy:cgood.product_buy,
                    product_detail:cgood.product_detail,
                    price:cgood.price,
                    sku_id:cgood.sku_id,
                    is_free_shipping:cgood.is_free_shipping,
                })
            } else {
                count++;
                if (count % 10 === 0) {
                    toast('未查询到订单状态！')
                    checkStatus = 1
                    recordInfo({
                        status:0,
                        status_name:'多次尝试，为查到订单状态！但已在结果页面！',
                        user_key:userkey,
                        user_info:radomAddr,
                        product_name:cgood.product_name,
                        product_id:cgood.product_id,
                        product_buy:cgood.product_buy,
                        product_detail:cgood.product_detail,
                        price:cgood.price,
                        sku_id:cgood.sku_id,
                        is_free_shipping:cgood.is_free_shipping,
                    })
                }
            }
        })
        if (checkStatus === 1) {
            break
        }
    }

    currentIndex++;

    while (true) {
        sleep(1000);
        userFindImg('huishouye.png', function (points) {
            logd('返回首页的查找' + JSON.stringify(points));
            if (points && points.length > 0) {
                logd(points[0])
                let x = parseInt((points[0].left + points[0].right) / 2 + '')
                let y = parseInt((points[0].top + points[0].bottom) / 2 + '')
                canGo = 1
                //点击坐标
                clickPoint(x, y)
                sleep(2000)
                judgeMainPage()
            } else {
                count++;
                if (count % 10 === 0) {
                    canGo = 1
                    toast('未找到回首页按钮！,此处调用返回！')
                    userBack()
                }
            }
        })
        if (checkStatus === 1) {
            break
        }
    }
}



function recordInfo(params){
    const result = usePost(host + apiUrl.record,params)
    if(result.code === 0){
        logd('上报成功！')
    }
}


function getUserRight() {
    logd("isServiceOk " + isServiceOk());
    startEnv()
    logd("isServiceOk " + isServiceOk());
    let request = image.requestScreenCapture(10000, 1);
    if (!request) {
        request = image.requestScreenCapture(10000, 1);
    }

    toast("申请截图结果... " + request)
    if (!request) {
        loge("申请截图权限失败,检查是否开启权限")
        exit()
    }
}

function userFindImg(imgName, cb) {
    let d = image.initOpenCV();
    logd(d)
//申请完权限至少等1s(垃圾设备多加点)再截图,否则会截不到图
    sleep(3000)
//从工程目录下res文件夹下读取sms.png文件
    let sms = readResAutoImage(imgName);
    //抓取屏幕
    let aimage = image.captureFullScreen();
    logd("aimage " + aimage);
    if (aimage != null) {
        //在图片中查找
        let points = image.findImage(aimage, sms, 0, 0, 0, 0, 0.7, 0.9, 1, 5);
        logd("points " + JSON.stringify(points));
        cb && cb(points)
        image.recycle(aimage)
    }
    //图片要回收
    image.recycle(sms)
}

main();